<template>
  <div>
    <el-card>
      <div style="display: flex; justify-content: space-between;">
        <el-statistic title="课程总数" :value="totalcourses" />
        <el-button type='warning' @click="handleAC">添加课程</el-button>
        <el-input v-model="searchQuery" placeholder="搜索课程..." style="width: 300px;" />
      </div>
    </el-card>
    <!-- 表格数据来源是后端查询的数据 -->
    <el-table :data="Courses" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="courseNum" label="课程编号" />
      <el-table-column prop="courseName" label="课程名称" />
      <el-table-column prop="coach" label="授课教练">
      </el-table-column>
      <el-table-column prop="price" label="￥价格" />
      <el-table-column label="操作">
        <!--  -->
        <template #default="scope">
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog v-model="addCourseDialogVisible" title="添加课程">
      <!-- 编辑表单 -->
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules"
      label-width="auto">
       <el-form-item label="课程名称" prop="courseName"> 
    <el-input v-model="ruleForm.courseName" />
  </el-form-item>
  
     <el-form-item label="授课教练" prop="coach">
    <el-select v-model="ruleForm.coach">
      <el-option 
        v-for="item in coachOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
  </el-form-item>
  
  <el-form-item label="￥价格" prop="price">
    <el-input v-model="ruleForm.price"/>
  </el-form-item>

      <el-form-item style="padding-left: 40%;">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">
          清空
        </el-button>
      </el-form-item>
    </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive} from 'vue'
import axios from 'axios'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { errorMessages } from 'vue/compiler-sfc'


// 定义响应式数组数据courses
const courses = ref([])
// 搜索会员响应数据
const searchQuery = ref('')

// 总会员数量 计算数组长度
const totalcourses = computed(() => courses.value.length)

const getAllCourses = (async()=>{
    // 获取course表 /api/courses是后端的相对地址
  const response = await axios.get('/api/courses')
  courses.value = response.data

})

  onMounted(()=> {
    getAllCourses()
})
//过滤数据表 将需要的输出 
const Courses = computed(() => {
    
    // 如果搜索的关键字的值为空 则返回所以数组值
  if (!searchQuery.value) return courses.value
// 否则返回搜索的  
  return courses.value.filter(course => 
//   通过课程名来过滤筛选
    course.courseName.includes(searchQuery.value) )
})
// 挂载后端请求的数据
// onMounted(async () => {

// })

// // 删除课程
const handleDelete = async (course) => {
    try{
  await axios.delete(`/api/courses/${course.courseNum}`)
  courses.value = courses.value.filter(c => c.courseNum !== course.courseNum)
  ElMessage.success('删除成功!')
    }catch(error){
        console.log(errorMessages)
    }
  // 再次渲染删除后的列表
  const update = await axios.get('/api/courses')
  courses.value = update.data

//   onMounted(() => {
//   handleDelete()
// })
}
// 页面数据
// const courseInfo = ref({
//     courseName: '',
//     coach: '',
//     price: '',
// })
// 编辑框是否可见 默认不可见
const addCourseDialogVisible = ref(false)
const handleAC = async () => {
  // 课程办理对话框弹出
  addCourseDialogVisible.value= true
}


interface RuleForm {
  courseName: string,
    coach: string,
    price: string     
}

const ruleForm = reactive<RuleForm>({
 courseName: '',
    coach: '',
    price: null,          
})

// 更新表单规则
const rules = reactive<FormRules<RuleForm>>({
  courseName: [ 
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    // { min: 2, max: 4, message: '姓名格式有误', trigger: 'blur' },
  ],
  coach: [  
    { required: true, message: '请选择授课教练', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
})
// ruleFormRef用于引用表单实例FormInstance
const ruleFormRef = ref<FormInstance>()

const coachOptions = ref([])
// 加载选项数据 请求后端
const loadOptions = async () => {
  try {
    // 请求后端 获取响应数据
    const coachRes = await axios.get('/api/employees/coaches')
    console.log(coachRes)
    // 处理健身卡选项
    coachOptions.value = coachRes.data.map(coach => ({
      label: coach.eeName,  // 使用 cardName 作为显示文本
      value: coach.eeName   // 使用 cardName 作为值
    }));
    
  } catch (error) {
    console.error('加载选项失败:', error);
    ElMessage.error('加载选项失败，请稍后重试');
  }
}
// 挂载
onMounted(() => {
  loadOptions()
})


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
        try{
        // 创建符合后端要求的数据结构
        const courseData = {
          courseName: ruleForm.courseName,
          coach: ruleForm.coach,
          price: ruleForm.price
        }
        
        await axios.post('/api/courses', courseData)
        console.log('办理成功!')
        ElMessage.success('添加成功!')
        formEl.resetFields()
      }catch(error){
        console.log(errorMessages)
    }
}
    // 再次渲染添加课程后的列表
  const update = await axios.get('/api/courses')
  courses.value = update.data

  })

}

// 重置表单函数
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // formEl.resetFields()：Element Plus 提供的表单重置方法
  formEl.resetFields()
}

</script>